package com.atg.atgchat.init.exception;

import com.atg.atgchat.init.common.vo.response.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/*
author: atg
time: 2025/1/16 16:32
*/
@Slf4j
@RestControllerAdvice
public class GlobalException {
    // 参数校验异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResult<?> handleConstraintViolationException(MethodArgumentNotValidException e) {
        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(error -> {
            String message = error.getDefaultMessage();
            errorMsg.append(message).append(",");
        });
        String message = errorMsg.toString();
        return ApiResult.fail(CommonErrorEnum.PARAM_VALID.getCode(),message.substring(0, message.length() - 1));
    }

    /**
     * 自定义校验异常（如参数校验等）
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = BusinessException.class)
    public ApiResult<?> businessExceptionHandler(BusinessException e) {
        log.info("business exception！The reason is：{}", e.getMessage(), e);
        return ApiResult.fail(e.getErrorCode(), e.getMessage());
    }
}
